/*
 *@Description: 数据库可复用操作方法
 *@Author: panlua
 *@Date: 2019-08-06 14:27:46
*/

const dbQuery = {
  /*
   *@name: 数据库数据转为 左右都加上 '  入库需要
   *@param:{type} 
   *@description:
   *@return:
   *@author: panlua
   *@date: 2019-08-06 15:13:19
  */
  string: (str) => {
    return `'${str}'`
  },
  /*
   *@name: 数据库新增复用方法
   *@param:{type} data：[Array->object]  例：[{value: 20, label: 'age'}, {value: '张三', label: 'name'}]  dsname：'数据表名称'
   *@description:
   *@return:
   *@author: panlua
   *@date: 2019-08-06 14:30:18
  */
  add: (data, dsname) => {
    return new Promise(async(reslove, reject) => {
      const labelArr = data.map(item => item.label)
      const valueArr = data.map(item => item.value)
      let sql = `insert into ${dsname} (${labelArr.join(', ')}) values (${valueArr.join(', ')})`
      const dbData = await $query(sql)
      if (dbData) {
        reslove(true)
      } else {
        reject(false)
      }
    })
  },
  /*
   *@name: 查询数据是否存在数据库
   *@param:{type} data：[Array->object]  例：[{value: 20, label: 'age'}, {value: '张三', label: 'name'}] dsname：'数据表名称'
   *@description:
   *@return: true：存在 false：不存在
   *@author: panlua
   *@date: 2019-08-06 14:33:00
  */
  findOne: (data, dsname) => {
    return new Promise(async(reslove, reject) => {
      let sql = `select count(*) as total from ${dsname} where `
      data.forEach((item, index) => {
        sql += `${item.label} = ${item.value}`
        if (index !== data.length - 1) {
          sql += ` and `
        }
      })
      const dbData = await $query(sql)
      if (dbData[0].total !== 0) {
        reslove(true)
      } else {
        reslove(false)
      }
    })
  },
  /*
   *@name: 查询数据
   *@param:{type} 
   *@description:
   *@return:
   *@author: panlua
   *@date: 2019-08-06 15:53:58
  */
  findData: (data, dsname) => {
    return new Promise(async(reslove, reject) => {
      let sql = `select * from ${dsname} where `
      data.forEach((item, index) => {
        sql += `${item.label} = ${item.value}`
        if (index !== data.length - 1) {
          sql += ` and `
        }
      })
      const dbData = await $query(sql)
      reslove(dbData)
    })
  }
}

module.exports = dbQuery